package com.okay.at;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.text.style.ReplacementSpan;

import androidx.core.content.ContextCompat;

import com.okay.util.DensityUtils;

public class RadiusBackgroundSpan extends ReplacementSpan {
    private int mTextColor;
    private int mTextSize;
    private int mPaddingHorizontal;
    private String mText;
    Context context;

    public RadiusBackgroundSpan(Context context, int textColor, int textSize, int paddingHorizontal, String text){
        this.context = context;
        mTextColor = textColor;
        mTextSize = textSize;
        mPaddingHorizontal = paddingHorizontal;
        mText = text;
    }

    @Override
    public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
        paint.setTextSize(mTextSize);

        Paint.FontMetricsInt metrics = paint.getFontMetricsInt();
        if (fm != null) {
            fm.top = metrics.top;
            fm.ascent = metrics.ascent;
            fm.descent = metrics.descent;
            fm.leading = metrics.leading;
            fm.bottom = metrics.bottom;
        }

        return (int) paint.measureText(mText) + 2*mPaddingHorizontal;
    }

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
        paint.setTextSize(mTextSize);
        paint.setAntiAlias(true);

        Paint.FontMetricsInt fontMetrics = paint.getFontMetricsInt();

        paint.setColor(ContextCompat.getColor(context,mTextColor));
        canvas.drawText(mText,x+mPaddingHorizontal,y+((fontMetrics.top-fontMetrics.ascent)/2)+ DensityUtils.dp2px(context,1),paint);
    }
}